const { promisePool, Pool } = require('../models/db')

const menuModel = require('../models/menuModel')

const JWT = require('../utils/JWT')

// 导入 bcryptjs 加密包
const bcrypt = require('bcryptjs')

const userService = {
  // 用户名是否被占用（同步方式演示）
  checkUser: (username, res) => {
    Pool.query(menuModel.checkByUsername, [username], function (err, rows) {
      if (err) {
        // return res.send({ code: 1, msg: err.msg })
        return res.codeMsg(err)
      }

      if (rows.length > 0) {
        // return resp.send({ code: 1, msg: '用户名被占用，请更换其他用户名！' })
        return res.codeMsg('用户名被占用，请更换其他用户名！')
      }
    })
  },

  // 插入新用户
  addUser: (username, password, res) => {
    Pool.query(
      menuModel.addUser,
      [{ username: username, password: password }],
      function (err, rows) {
        if (err) {
          return res.codeMsg(err)
        }

        if (rows.affectedRows !== 1) {
          return res.codeMsg('注册用户失败，请稍后再试！')
        }

        // 注册成功提示
        // res.send({ code: 0, msg: '注册成功！' })
        return res.codeMsg('注册成功！', 0)
      }
    )
  },

  // 用户登录
  loginUser: (username, password, res) => {
    Pool.query(menuModel.checkByUsername, [username], function (err, rows) {
      if (err) {
        return res.codeMsg(err)
      }

      // 用户是否存在
      if (rows.length !== 1) {
        return res.codeMsg('用户名不存在！')
      }

      // 密码是否正确（使用✨bcrypt.compareSync()对密码进行比较）
      const compareResult = bcrypt.compareSync(password, rows[0].password)

      if (!compareResult) {
        return res.codeMsg('密码错误！')
      }

      // 🚩设置token签名
      // 1、生成token
      const user = { ...rows[0], password: '', user_pic: '' } // 利用展开运算符的方式排出密码、照片等敏感信息
      const tokenStr = JWT.generate(user)

      // 2、发送token到客户端（header方式）
      // res.header('Authorization', token)
      return res.send({
        code: 0,
        msg: '登录成功',
        data: {
          token: 'Bearer ' + tokenStr,
          account: username,
        }
      })

      // 登录成功
      // res.codeMsg('登录成功', 0)
    })
  },

  // 获取用户id
  getMenuId: (req, res) => {
    console.log(req.body, 'req.body');
    // return res.send({
    //   code: 0,
    //   msg: '成功',
    //   data: [3, 2, 12, 10, 15, 21, 22, 23, 1, 31]
    // })
    Pool.query(menuModel.getMenuId, [req.body.user_id], function (err, rows) {
      console.log(err, 'err');
      if (err) {
        return res.codeMsg(err)
      }

      // 2、发送token到客户端（header方式）
      // res.header('Authorization', token)
      console.log(rows[0]);
      const data = rows[0].user_id_array ? rows[0].user_id_array.split(',').map(Number) : rows[0].user_id_array
      return res.send({
        code: 0,
        msg: '登录成功',
        data
      })

      // 登录成功
      // res.codeMsg('登录成功', 0)
    })
  },
  menuTreeAll: (res) => {
    console.log(222);
    return res.send({
      code: 0,
      msg: '成功',
      data:  [
            {
                "id": 1,
                "pid": 0,
                "status": 1,
                "type": 0,
                "code": "A01",
                "name": "基础管理",
                "identification": null,
                "url": "sys",
                "icon": "base",
                "memo": "sys",
                "sort": 2,
                "creator_id": 1,
                "updater_id": 1,
                "created_at": "2023-11-24 15:44:08",
                "updated_at": "2023-11-24 15:44:08",
                "children": [
                    {
                        "id": 3,
                        "pid": 1,
                        "status": 1,
                        "type": 1,
                        "code": "A0102",
                        "name": "用户管理",
                        "identification": null,
                        "url": "/sys/user",
                        "icon": "roleManage",
                        "memo": null,
                        "sort": 2,
                        "creator_id": 1,
                        "updater_id": 1,
                        "created_at": "2023-11-24 15:44:08",
                        "updated_at": "2023-11-24 15:44:08",
                        "children": []
                    },
                    {
                        "id": 2,
                        "pid": 1,
                        "status": 1,
                        "type": 1,
                        "code": "A0101",
                        "name": "菜单管理",
                        "identification": null,
                        "url": "/sys/menu",
                        "icon": "menu",
                        "memo": null,
                        "sort": 1,
                        "creator_id": 1,
                        "updater_id": 1,
                        "created_at": "2023-11-24 16:06:05",
                        "updated_at": "2023-11-24 16:06:10",
                        "children": []
                    },
                    {
                        "id": 31,
                        "pid": 1,
                        "status": 1,
                        "type": 1,
                        "code": null,
                        "name": "配置项管理",
                        "identification": null,
                        "url": "sys/system-item-setting",
                        "icon": "base",
                        "memo": null,
                        "sort": null,
                        "creator_id": 1,
                        "updater_id": 1,
                        "created_at": "2024-04-08 13:42:03",
                        "updated_at": "2024-04-08 13:42:21",
                        "children": []
                    }
                ]
            },
            {
                "id": 12,
                "pid": 0,
                "status": 1,
                "type": 0,
                "code": null,
                "name": "种植区域管理",
                "identification": null,
                "url": "tree",
                "icon": "tree",
                "memo": "种植管理",
                "sort": 1,
                "creator_id": 1,
                "updater_id": 1,
                "created_at": "2024-03-12 09:47:27",
                "updated_at": "2024-03-12 15:43:17",
                "children": [
                    {
                        "id": 10,
                        "pid": 12,
                        "status": 1,
                        "type": 1,
                        "code": null,
                        "name": "种植区域",
                        "identification": null,
                        "url": "/tree/area",
                        "icon": "area",
                        "memo": "种植区域",
                        "sort": 4,
                        "creator_id": 1,
                        "updater_id": 1,
                        "created_at": "2024-03-12 09:43:40",
                        "updated_at": "2024-03-13 09:27:23",
                        "children": []
                    },
                    {
                        "id": 15,
                        "pid": 12,
                        "status": 1,
                        "type": 1,
                        "code": null,
                        "name": "种植树种",
                        "identification": null,
                        "url": "/tree/treeList",
                        "icon": "tree",
                        "memo": "种植树种",
                        "sort": 2,
                        "creator_id": 1,
                        "updater_id": 1,
                        "created_at": "2024-03-12 09:51:02",
                        "updated_at": "2024-03-12 15:43:36",
                        "children": []
                    },
                    {
                        "id": 21,
                        "pid": 12,
                        "status": 1,
                        "type": 1,
                        "code": null,
                        "name": "种植规格",
                        "identification": null,
                        "url": "/tree/specList",
                        "icon": "spec",
                        "memo": "种植规格",
                        "sort": 1,
                        "creator_id": 1,
                        "updater_id": 1,
                        "created_at": "2024-03-12 14:26:48",
                        "updated_at": "2024-03-13 09:30:18",
                        "children": []
                    }
                ]
            },
            {
                "id": 22,
                "pid": 0,
                "status": 1,
                "type": 0,
                "code": null,
                "name": "捐赠管理",
                "identification": null,
                "url": "donate",
                "icon": "juan",
                "memo": "捐赠管理",
                "sort": 0,
                "creator_id": 1,
                "updater_id": 1,
                "created_at": "2024-03-12 15:45:35",
                "updated_at": "2024-03-13 09:26:21",
                "children": [
                    {
                        "id": 23,
                        "pid": 22,
                        "status": 1,
                        "type": 1,
                        "code": null,
                        "name": "捐赠记录",
                        "identification": null,
                        "url": "/donate/record",
                        "icon": "juan",
                        "memo": "捐赠记录",
                        "sort": null,
                        "creator_id": 1,
                        "updater_id": 1,
                        "created_at": "2024-03-12 15:46:31",
                        "updated_at": "2024-03-13 09:26:40",
                        "children": []
                    }
                ]
            }
        ]
    })
    Pool.query(menuModel.checkByUsername, [username], function (err, rows) {
      if (err) {
        return res.codeMsg(err)
      }

      // 用户是否存在
      if (rows.length !== 1) {
        return res.codeMsg('用户名不存在！')
      }

      // 密码是否正确（使用✨bcrypt.compareSync()对密码进行比较）
      const compareResult = bcrypt.compareSync(password, rows[0].password)

      if (!compareResult) {
        return res.codeMsg('密码错误！')
      }

      // 🚩设置token签名
      // 1、生成token
      const user = { ...rows[0], password: '', user_pic: '' } // 利用展开运算符的方式排出密码、照片等敏感信息
      const tokenStr = JWT.generate(user)

      // 2、发送token到客户端（header方式）
      // res.header('Authorization', token)
      return res.send({
        code: 0,
        msg: '登录成功',
        data: {
          token: 'Bearer ' + tokenStr,
          account: username
        }
      })

      // 登录成功
      // res.codeMsg('登录成功', 0)
    })
  },
  // menuTreeUser
  menuTreeUser: (res) => {
    console.log(222);
    return res.send({
      code: 0,
      msg: '成功',
      data:  [
              {
                "id": 1,
                "pid": 0,
                "status": 1,
                "type": 0,
                "code": "A01",
                "name": "基础管理",
                "identification": null,
                "url": "sys",
                "icon": "base",
                "memo": "sys",
                "sort": 2,
                "creator_id": 1,
                "updater_id": 1,
                "created_at": "2023-11-24 15:44:08",
                "updated_at": "2023-11-24 15:44:08",
                "children": [
                  {
                    "id": 3,
                    "pid": 1,
                    "status": 1,
                    "type": 1,
                    "code": "A0102",
                    "name": "用户管理",
                    "identification": null,
                    "url": "/sys/user",
                    "icon": "roleManage",
                    "memo": null,
                    "sort": 2,
                    "creator_id": 1,
                    "updater_id": 1,
                    "created_at": "2023-11-24 15:44:08",
                    "updated_at": "2023-11-24 15:44:08",
                    "children": []
                  },
                  {
                    "id": 2,
                    "pid": 1,
                    "status": 1,
                    "type": 1,
                    "code": "A0101",
                    "name": "菜单管理",
                    "identification": null,
                    "url": "/sys/menu",
                    "icon": "menu",
                    "memo": null,
                    "sort": 1,
                    "creator_id": 1,
                    "updater_id": 1,
                    "created_at": "2023-11-24 16:06:05",
                    "updated_at": "2023-11-24 16:06:10",
                    "children": []
                  },
                  {
                    "id": 31,
                    "pid": 1,
                    "status": 1,
                    "type": 1,
                    "code": null,
                    "name": "配置项管理",
                    "identification": null,
                    "url": "sys/system-item-setting",
                    "icon": "base",
                    "memo": null,
                    "sort": null,
                    "creator_id": 1,
                    "updater_id": 1,
                    "created_at": "2024-04-08 13:42:03",
                    "updated_at": "2024-04-08 13:42:21",
                    "children": []
                  }
                ]
              },
              {
                "id": 12,
                "pid": 0,
                "status": 1,
                "type": 0,
                "code": null,
                "name": "种植区域管理",
                "identification": null,
                "url": "tree",
                "icon": "tree",
                "memo": "种植管理",
                "sort": 1,
                "creator_id": 1,
                "updater_id": 1,
                "created_at": "2024-03-12 09:47:27",
                "updated_at": "2024-03-12 15:43:17",
                "children": [
                  {
                    "id": 10,
                    "pid": 12,
                    "status": 1,
                    "type": 1,
                    "code": null,
                    "name": "种植区域",
                    "identification": null,
                    "url": "/tree/area",
                    "icon": "area",
                    "memo": "种植区域",
                    "sort": 4,
                    "creator_id": 1,
                    "updater_id": 1,
                    "created_at": "2024-03-12 09:43:40",
                    "updated_at": "2024-03-13 09:27:23",
                    "children": []
                  },
                  {
                    "id": 15,
                    "pid": 12,
                    "status": 1,
                    "type": 1,
                    "code": null,
                    "name": "种植树种",
                    "identification": null,
                    "url": "/tree/treeList",
                    "icon": "tree",
                    "memo": "种植树种",
                    "sort": 2,
                    "creator_id": 1,
                    "updater_id": 1,
                    "created_at": "2024-03-12 09:51:02",
                    "updated_at": "2024-03-12 15:43:36",
                    "children": []
                  },
                  {
                    "id": 21,
                    "pid": 12,
                    "status": 1,
                    "type": 1,
                    "code": null,
                    "name": "种植规格",
                    "identification": null,
                    "url": "/tree/specList",
                    "icon": "spec",
                    "memo": "种植规格",
                    "sort": 1,
                    "creator_id": 1,
                    "updater_id": 1,
                    "created_at": "2024-03-12 14:26:48",
                    "updated_at": "2024-03-13 09:30:18",
                    "children": []
                  }
                ]
              },
              {
                "id": 22,
                "pid": 0,
                "status": 1,
                "type": 0,
                "code": null,
                "name": "捐赠管理",
                "identification": null,
                "url": "donate",
                "icon": "juan",
                "memo": "捐赠管理",
                "sort": 0,
                "creator_id": 1,
                "updater_id": 1,
                "created_at": "2024-03-12 15:45:35",
                "updated_at": "2024-03-13 09:26:21",
                "children": [
                  {
                    "id": 23,
                    "pid": 22,
                    "status": 1,
                    "type": 1,
                    "code": null,
                    "name": "捐赠记录",
                    "identification": null,
                    "url": "/donate/record",
                    "icon": "juan",
                    "memo": "捐赠记录",
                    "sort": null,
                    "creator_id": 1,
                    "updater_id": 1,
                    "created_at": "2024-03-12 15:46:31",
                    "updated_at": "2024-03-13 09:26:40",
                    "children": []
                  }
                ]
              }
            ]
    })
    Pool.query(menuModel.checkByUsername, [username], function (err, rows) {
      if (err) {
        return res.codeMsg(err)
      }

      // 用户是否存在
      if (rows.length !== 1) {
        return res.codeMsg('用户名不存在！')
      }

      // 密码是否正确（使用✨bcrypt.compareSync()对密码进行比较）
      const compareResult = bcrypt.compareSync(password, rows[0].password)

      if (!compareResult) {
        return res.codeMsg('密码错误！')
      }

      // 🚩设置token签名
      // 1、生成token
      const user = { ...rows[0], password: '', user_pic: '' } // 利用展开运算符的方式排出密码、照片等敏感信息
      const tokenStr = JWT.generate(user)

      // 2、发送token到客户端（header方式）
      // res.header('Authorization', token)
      return res.send({
        code: 0,
        msg: '登录成功',
        data: {
          token: 'Bearer ' + tokenStr,
          account: username
        }
      })

      // 登录成功
      // res.codeMsg('登录成功', 0)
    })
  },
}

module.exports = userService
